package com.lanyou.esb.cook.proxy.redis.proxy.impl;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.lanyou.esb.cook.proxy.common.Constants4Redis;
import com.lanyou.esb.cook.proxy.redis.JedisPoolUtils;
import com.lanyou.esb.cook.proxy.redis.proxy.base.BaseStrJedisProxy;

/**
 * 服务器时间Redis操作代理
 * 
 * @author Davey.wu
 */
public class ServiceTimeJedisProxy extends BaseStrJedisProxy<Long> {

	public ServiceTimeJedisProxy() {
		this.setPrefix(Constants4Redis.PREFIX_COOKPROXY_SERVICE_TIME);
	}

	@Override
	public long setex(String key, Long value) throws JedisException,
			JsonProcessingException {
		if (value == null) {
			return 0;
		}
		String result = "";
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return 0;
		}
		boolean broken = false;
		try {
			result = jedis.set(key, value.toString());
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}

		if (StringUtils.isNotBlank(result)) {
			return 1l;
		}
		return 0;
	}

	@Override
	public Long get(String key) throws JsonParseException,
			JsonMappingException, IOException {
		String result = "";
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return 0l;
		}
		boolean broken = false;
		try {
			result = jedis.get(key);
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		try {
			return Long.parseLong(result);
		} catch (Exception e) {
			return 0l;
		}
	}

	@Override
	public String getKey(String field) {
		return this.getPrefix();
	}

	@Override
	public String getKeyFromObject(Long value) {
		return this.getPrefix();
	}
}
